package com.jz.netthings.engine.netty;

import com.jz.netthings.appengine.baseData.MachineData;
import com.jz.netthings.appengine.queue.MachineMgr;
import com.jz.netthings.engine.service.ClientService;
import com.jz.netthings.engine.service.ZxdcChairService;
import com.jz.netthings.engine.service.ZxdcService;
import com.jz.netthings.engine.sqlite.service.GetMachineLogToDataBaseService;
import com.jz.netthings.exception.AdscmSystemException;
import com.jz.netthings.netty.protocol.BasePacket;
import com.jz.netthings.netty.protocol.bean.*;
import com.jz.netthings.netty.support.Attributes;
import com.jz.netthings.netty.support.ServerHandlerSupport;
import com.jz.netthings.netty.utils.NettyMsgHelper;
import com.jz.netthings.utils.AdscmBaseUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;

@Component("nettyServerHandlerSupport")
public class NettyServerHandlerSupport implements ServerHandlerSupport {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    ClientService clientService;
    @Autowired
    ZxdcService zxdcService;
    @Autowired
    ZxdcChairService zxdcChairService;

    @Autowired
    RedisTemplate<Object, Object> objectRedisTemplate;
    @Autowired
    GetMachineLogToDataBaseService getMachineLogToDataBaseService;

    @Override
    public BasePacket handlePacket(BasePacket soursePacket) {

        BasePacket targetPacket = null;

        if (soursePacket == null) {
            targetPacket = new ErrorMsgResponsePacket("请求包为 Null，处理请求失败...");
        } else {
            if (soursePacket instanceof LoginRequestPacket) {
                //登录请求
                LoginRequestPacket packet = (LoginRequestPacket) soursePacket;

                targetPacket = clientService.clientUserLogin(packet);
            } else if (soursePacket instanceof FaceValidateRequestPacket) {
                //人脸认证请求
                FaceValidateRequestPacket packet = (FaceValidateRequestPacket) soursePacket;

                targetPacket = clientService.clientFaceValidate(packet);
            } else if (soursePacket instanceof ZxdcLoginPacket) {
                //单采机登录，什么都不返回
                ZxdcLoginPacket packet = (ZxdcLoginPacket) soursePacket;

                zxdcService.handlerLoginPacket((ZxdcLoginPacket) soursePacket);

            } else if (soursePacket instanceof ZxdcMsgPacket) {
                //单采机的其他数据包
                targetPacket = zxdcService.handlerMsgPacket((ZxdcMsgPacket) soursePacket);
            }

        }

        return targetPacket;
    }

    @Override
    public ZxdcMsgPacket handleChairPacket(ZxdcMsgPacket soursePacket) {
        return zxdcChairService.handleChairPacket(soursePacket);
    }

    @Override
    public void cleanRedisObj(String key) throws AdscmSystemException {
        AdscmBaseUtils.getInstance().cleanObjFromRedis(key, objectRedisTemplate);
    }

    @Override
    public void freeMachineData(ChannelHandlerContext ctx) throws AdscmSystemException {
        try {
            MachineData machine = MachineMgr.getInstance().getMachine(ctx);
            synchronized (MachineMgr.getInstance()) {
                if (machine != null) {
                    machine.setOnline(false);
                    MachineMgr.getInstance().updateRedisMachineData(objectRedisTemplate,machine);
                }
            }

            List<ChannelHandlerContext> allotCtxs = MachineMgr.getInstance().getAllotCtxs();
            synchronized (MachineMgr.getInstance()) {
                Iterator<ChannelHandlerContext> iterator = allotCtxs.iterator();
                while (iterator.hasNext()) {
                    ChannelHandlerContext next = iterator.next();
                    if (ctx == next) {
                        iterator.remove();
                    }
                }

            }


        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new AdscmSystemException(e.getMessage());
        }
    }

    @Override
    public void doAnalysisZxdcDB(String oldFileName, String newFilePath) throws Exception {
       logger.info("单采机数据库文件【"+oldFileName+"："+newFilePath+"】上传成功，开始解析数据库文件...");
        getMachineLogToDataBaseService.getMachineLogToDataBase(oldFileName,newFilePath);
    }
}
